package com.xsq.rpc.consumer.rpc;


import com.xsq.rpc.common.consumer.UserClientHandler;
import com.xsq.rpc.common.model.RPCNettyClient;
import com.xsq.rpc.common.util.RpcRequestEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @ClassName RpcClient
 * @Description TODO
 * @Author xsq
 * @Date 2020/5/30 16:13
 **/
public class RpcClient {

    /**
     * 初始化客户端
     */
    public static RPCNettyClient initClient(String hostName, int port) {
        final UserClientHandler client = new UserClientHandler();
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //对RpcRequest实体编码发送给服务端,用StringDecoder解码接收服务端发送的字符串
                        pipeline.addLast(new RpcRequestEncoder())
                                .addLast(new StringDecoder())
                                .addLast(client);

                    }
                });
        try {
            bootstrap.connect(hostName, port).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new RPCNettyClient(client,group);
    }
}
